<!--
 * @Description:
 * @Author: william
 * @Date: 2025-02-17 16:47:40
 * @LastEditors: william
 * @LastEditTime: 2025-08-29 15:51:15
-->
<template>
  <BaseDialog v-model="dialogVisible" :title="title" style="width: 850px" width="850px" :before-close="handleClose">
    <TravelDialog ref="refChildForm" :type="props.type" :row="props.row" />
    <el-form ref="refDialogForm" class="set-dialog-form" :label-width="language === 'en' ? '180px' : '80px'"
      :model="formData" :rules="rules">
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('fleet.passingScenery')" prop="through">
            <TextInput v-model="formData.through" type="textarea" :maxlength="512" :rows="4"
              :label="$t('fleet.passingScenery')">
              <template #suffix>{{ $t('fleet.kilometer') }}</template>
            </TextInput>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="form-dialog-footer">
        <el-button plain @click="handleClose">{{
          $t('public.cancel')
          }}</el-button>
        <el-button type="primary" @click="handleSubmitForm">{{
          $t('public.confirm')
          }}</el-button>
      </div>
    </template>
  </BaseDialog>
</template>

<script setup>
import TravelDialog from './TravelDialog.vue'
const props = defineProps({
  type: {
    type: String,
    default: 'add' // add | edit
  },
  row: {
    type: Object,
    default: () => { }
  }
})

const emit = defineEmits(['add', 'update'])
const dialogVisible = defineModel({
  type: Boolean,
  default: false
})
const { language } = storeToRefs(useAppStore())
const title = computed(() =>
  props.type === 'add' ? g_t('travelAgency.addRoute') : g_t('travelAgency.editRoute')
)

const refChildForm = ref(null)
const refDialogForm = ref(null)
const formData = ref({
  through: ''
})
const rules = {}

onMounted(async () => {
  if (props.type === 'edit') {
    g_utils.assignFormData(formData.value, props.row)
    props.row.id && (formData.value.id = props.row.id)
    console.log('parentForm.value', formData.value)
  }
})

const handleClose = _ => {
  dialogVisible.value = false
}

const handleSubmitForm = () => {
  refChildForm.value.formData.dayIndex = refChildForm.value.formData.dayIndex ? Number(refChildForm.value.formData.dayIndex) : ''
  const newFormData = {
    ...refChildForm.value.formData,
    ...formData.value
  }
  console.log('newFormData', newFormData)
  Promise.all([
    refChildForm.value.refDialogForm.validate(),
    refDialogForm.value.validate()
  ])
    .then(() => {
      console.log('所有表单验证通过')
      // 都没填写不需要保存
      const valid2 = Object.keys(newFormData).some(k => {
        return newFormData[k].length
      })
      handleClose()
      valid2 && emit(props.type === 'add' ? 'add' : 'update', newFormData)
    })
    .catch(() => {
      console.log('有表单验证未通过')
    })
}
</script>

<style scoped lang="scss"></style>
